package com.songqi.common.web.request.i18n;


import lombok.Data;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: songqi(13776346982)
 * @date: 2022/10/10 15:12
 */
@Data
public class HeaderLocaleResolver implements LocaleResolver {

    private Locale defaultLocale;

    private String headerName;

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        Enumeration<String> requestLocaleNames = request.getHeaders(this.headerName);
        if(requestLocaleNames == null){
            return this.defaultLocale;
        }
        List<String> requestLocaleNameList = Collections.list(requestLocaleNames);
        return this.resolveSupportedLocale(requestLocaleNameList);
                
    }

    private Locale resolveSupportedLocale(List<String> requestLocaleNameList) {
        List<Locale> requestLocales = parseLocale(requestLocaleNameList);
        if(CollectionUtils.isEmpty(requestLocales)){
            return this.defaultLocale;
        }
        return requestLocales.get(0);
    
    }

    private List<Locale> parseLocale(List<String> requestLocaleNameList) {
        if(CollectionUtils.isEmpty(requestLocaleNameList)){
            return null;
        }
        return requestLocaleNameList.stream().map(Locale::forLanguageTag).filter(requestLocaleName ->
                StringUtils.hasText(requestLocaleName.getDisplayName())).collect(Collectors.toList());
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}
